package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.shopCarMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.service.impl.orderServiceImpl;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user/order")
@Api("用户端订单接口")
@Slf4j
public class orderController {
    @Autowired
    private orderServiceImpl orderService;
    @Autowired
    private com.sky.mapper.orderMapper orderMapper;
    @Autowired
    private shopCarMapper shopCarMapper;

    @PostMapping("/submit")
    @ApiOperation(value = "用户下单")
    public Result<OrderSubmitVO> orderSubmit(@RequestBody OrdersSubmitDTO ordersSubmitDTO) {
        OrderSubmitVO orderSubmitVO = orderService.submitOrder(ordersSubmitDTO);
        return Result.success(orderSubmitVO);
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @PutMapping("/payment")
    @ApiOperation("订单支付")
    public Result<OrderPaymentVO> payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        log.info("订单支付：{}", ordersPaymentDTO);
        OrderPaymentVO orderPaymentVO = orderService.payment(ordersPaymentDTO);
        log.info("生成预支付交易单：{}", orderPaymentVO);
        return Result.success(orderPaymentVO);
    }

    @ApiOperation(value = "历史订单")
    @GetMapping("/historyOrders")
    public Result<PageResult> historyOrders(int page, int pageSize, Integer status) {
        PageResult pageResult = orderService.pageQuery4User(page, pageSize, status);
        return Result.success(pageResult);
    }
    @ApiOperation(value = "取消订单")
    @PutMapping("/cancel/{id}")
    public Result<Orders> cancelOrder(@PathVariable Long id) throws Exception {
        orderService.cancel(id);
        return Result.success();
    }

    @ApiOperation(value = "查看订单详情")
    @GetMapping("/orderDetail/{id}")
    public Result orderDetail(@PathVariable Long id) {
        Orders byId = orderMapper.findById(id.intValue());
        OrderVO orderVO = new OrderVO();
        List<OrderDetail> listOrderDetailByOrderId = orderMapper.getListOrderDetailByOrderId(byId.getNumber());
        BeanUtils.copyProperties(byId,orderVO);
        orderVO.setOrderDetailList(listOrderDetailByOrderId);
        return Result.success(orderVO);
    }

    @PostMapping("/repetition/{id}")
    @ApiOperation("再来一单")
    public Result repetition(@PathVariable Long id) {
       /* Orders byId = orderMapper.findById(id.intValue());
        OrdersSubmitDTO ordersSubmitDTO = new OrdersSubmitDTO();
        BeanUtils.copyProperties(byId,ordersSubmitDTO);
        //ordersSubmitDTO.set
        // 在当前时间基础上加1小时
        LocalDateTime timePlusOneHour = LocalDateTime.now().plusHours(1);
        ordersSubmitDTO.setEstimatedDeliveryTime(timePlusOneHour);
        //得到该订单的菜品信息
        // 将该订单的菜品添加进入购物车
        orderMapper.getListOrderDetailByOrderId(byId.getNumber()).forEach(orderDetail -> {
            ShoppingCart shoppingCart=new ShoppingCart();
            orderDetail.setId(null);
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shopCarMapper.insert(shoppingCart);
        });
       *//* //调用用户下单方法
        OrderService.submitOrder(ordersSubmitDTO);*//*
        return Result.success();*/
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderMapper.getListOrderDetailByOrderId(String.valueOf(id));

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shopCarMapper.insertBatch(shoppingCartList);
        return Result.success();
    }

    @GetMapping("/reminder/{id}")
    public  Result remindOrder(@PathVariable Long id) {
        Result result = orderService.orderRemind(id.longValue());
        return result;

    }
}
